/*
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package hextd.util;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class ImagePanel extends JPanel {

	private ImageIcon image;

	public ImagePanel() {
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		if (image != null) {
			Graphics2D g2 = (Graphics2D) g;
			int pWidth = getWidth();
			int pHeight = getHeight();
			float pRatio = (float) pWidth / pHeight;
			int iWidth = image.getIconWidth();
			int iHeight = image.getIconHeight();
			float iRatio = (float) iWidth / iHeight;
			Color oldColor = g2.getColor();
			g2.setColor(getBackground());
			g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
			g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
			if (iRatio > pRatio) {
				g2.drawRect(0, 0, pWidth, pHeight);
				int newHeight = (int) (pWidth / iRatio);
				int offset = (pHeight - newHeight) / 2;
				g2.drawImage(image.getImage(), 0, offset, pWidth, newHeight, this);
			} else {
				g2.drawRect(0, 0, pWidth, pHeight);
				int newWidth = (int) (pHeight * iRatio);
				int offset = (pWidth - newWidth) / 2;
				g2.drawImage(image.getImage(), offset, 0, newWidth, pHeight, this);
			}
			g2.setColor(oldColor);
		}
	}

	/**
	 * @return the image
	 */
	public ImageIcon getImage() {
		return image;
	}

	/**
	 * @param image the image to set
	 */
	public void setImage(ImageIcon image) {
		this.image = image;
	}
}
